<script lang="ts" setup>
import { ECharts, EChartsOption, init } from 'echarts'

// 定义props
interface Props {
  width?: string
  /** 高度 */
  height?: string
  /** 图表配置项 */
  option?: EChartsOption
  /** 标题 */
  title?: string
  /** 简单模式 */
  simple?: boolean
}
const themeStore = useThemeStoreHook()
const themeToken = useThemeStoreHook().getThemeToken()
const props = withDefaults(defineProps<Props>(), {
  height: '100%',
  width: '100%'
})

const myChartsRef = ref<HTMLDivElement>()
let myChart: ECharts
// eslint-disable-next-line no-undef
let timer: string | number | NodeJS.Timeout | undefined
// 初始化echarts
const initChart = (): void => {
  if (myChart !== undefined) {
    myChart.dispose()
  }
  myChart = init(myChartsRef.value as HTMLDivElement, themeStore.themeType)
  // 拿到option配置项，渲染echarts
  myChart?.setOption(
    {
      backgroundColor: 'transparent',
      ...props.option
    },
    true
  )
}

// 重新渲染echarts
const resizeChart = (): void => {
  timer = setTimeout(() => {
    if (myChart) {
      myChart.resize()
    }
  }, 500)
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  clearTimeout(timer as any)
  timer = 0
})

watch(
  () => themeStore,
  () => {
    initChart()
  },
  {
    deep: true
  }
)

watch(
  props.option,
  () => {
    initChart()
  },
  {
    deep: true
  }
)
</script>

<template>
  <a-card v-if="!simple" class="echarts-box">
    <div class="echarts-box-header">
      <div
        v-show="title"
        :style="{
          color: themeToken.colorText
        }"
        class="title"
      >
        {{ title }}
      </div>
      <div class="right">
        <slot name="header"></slot>
      </div>
    </div>
    <div ref="myChartsRef" :style="{ height: height, width: width }" />
  </a-card>
  <div v-else ref="myChartsRef" :style="{ height: height, width: width }" />
</template>

<style scoped>
:deep(.ant-card-body) {
  padding: 15px;
}
.echarts-box {
  width: 100%;
  box-sizing: border-box;
  .echarts-box-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }
}
</style>
